/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.awt.Image;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.print.DocFlavor;

/**
 *主要存放一个地图，根据该地图绘制图形
 * @author 林景富
 */
public class Model extends Observable{

    private char[][] map=null;
    private HashMap<Character,Image> imageMap=new HashMap<>();//为了便于获取图片使用HashMap来存储图片
    private boolean sizeChange=false;

    public Model(){
        
        this.loadImages();
      
        this.loadMap(System.getProperty("user.dir")+"/maps/map1.txt");
 
      
    }
    /**
     * 把地图上用到的地图预先加载进来
     */
    private void loadImages(){
        String path=System.getProperty("user.dir")+"/images";
        File filepath=new File(path);
        File[] files=filepath.listFiles();
        for(File file:files){
            try {
                Image image=ImageIO.read(file);
                Character index=file.getName().charAt(0);
                this.imageMap.put(index, image);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        
    }
    
    /**
     * 根据指定路径加载地图到二维数组中
     * @param path  地图文件所在路径
     * @throws FileNotFoundException 
     */
    public void loadMap(String path){
        try {
            Scanner input=new Scanner(new File(path));
            String line=input.nextLine();
            int cols=line.length();//地图列数
            int rows=1;//地图行数
            while(input.hasNext()){
                input.nextLine();
                rows++;
            }
            this.map=new char[rows][cols];
            input.close();
            input=new Scanner(new File(path));
            int i=0;
            while(input.hasNext()){
                line=input.nextLine();
                this.map[i++]=line.toCharArray();
            }
            input.close();
            
            //每次导入新地图，则地图尺寸可能会变化，因此需要通知框架改变自己的大小
            this.sizeChange=true;
            this.setChanged();
            this.notifyObservers();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }
    
    public char[][] getMap() {
        return map;
    }

    public HashMap<Character, Image> getImageMap() {
        return imageMap;
    }
    
        public boolean isSizeChange() {
        return sizeChange;
    }

    public void setSizeChange(boolean sizeChange) {
        this.sizeChange = sizeChange;
    }
}
